package cn.itsource.user.service.impl;

import cn.itsource.basic.util.AxajResult;
import cn.itsource.basic.util.MD5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.user.domain.LoginInfo;
import cn.itsource.user.domain.dto.UserDto;
import cn.itsource.user.mapper.LoginInfoMapper;
import cn.itsource.user.service.ILoginInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginInfoServiceImpl implements ILoginInfoService {
    @Autowired
    private LoginInfoMapper loginInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public AxajResult login(UserDto userDto) {
        //校验用户信息
        LoginInfo loginInfo=checkMsg(userDto);
        //随机产生token值
        String token=StrUtils.getComplexRandomString(4);
        //将对象存放在Redis中(存活时间为30分钟)
        redisTemplate.opsForValue().set(token, loginInfo,30, TimeUnit.MINUTES);
        //将token值和loginInfo放在map中传递给前端
        Map map= new HashMap<>();
        map.put("token", token);
        map.put("loginUser", loginInfo);
        return new AxajResult().setObjResult(map);
    }

    private LoginInfo checkMsg(UserDto userDto) {
        //判断信息是否为空
        if(StringUtils.isEmpty(userDto.getUsername())||StringUtils.isEmpty(userDto.getPassword())
                ||userDto.getType()==null){
            throw new RuntimeException("请填写完整信息");
        }
        //通过用户名和类型查询该用户是否存在
        LoginInfo loginInfo=loginInfoMapper.findByUserDto(userDto);
        //验证用户名
        if(loginInfo==null){
            throw new RuntimeException("用户名错误");
        };
        //验证用户是否被禁用
        if(!loginInfo.getDisable()){
            throw new RuntimeException("该用户已被禁用，请联系管理人员");
        }
        //验证密码是否正确
        if(!loginInfo.getPassword().equals(MD5Utils.encrypByMd5(userDto.getPassword()+loginInfo.getSalt()))){
            throw new RuntimeException("密码不正确");
        }
        return loginInfo;
    }
}
